package com.qianying.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.qianying.comment.CommonResult;
import com.qianying.entity.UserWorkType;
import com.qianying.entity.WorkType;
import com.qianying.mapper.WorkTypeMapper;
import com.qianying.service.WorkTypeService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * 工种类型服务实现类
 * 实现工种类型相关的业务逻辑
 */
@Service
public class WorkTypeServiceImpl extends ServiceImpl<WorkTypeMapper, WorkType> implements WorkTypeService {

    @Autowired
    private WorkTypeMapper workTypeMapper;

    /**
     * 分页查询工种类型列表
     */
    @Override
    public CommonResult<IPage<WorkType>> getPage(Page<WorkType> page, String typeName) {
        LambdaQueryWrapper<WorkType> queryWrapper = new LambdaQueryWrapper<>();
        // 模糊查询条件
        if (StringUtils.hasText(typeName)) {
            queryWrapper.like(WorkType::getTypeName, typeName);
        }
        // 按ID升序排序
        queryWrapper.orderByAsc(WorkType::getId);
        // 执行分页查询
        IPage<WorkType> resultPage = workTypeMapper.selectPage(page, queryWrapper);
        return CommonResult.success(resultPage);
    }

    /**
     * 根据ID查询工种类型详情
     */
    @Override
    public CommonResult<WorkType> getById(Long id) {
        // 空值校验
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }
        // 查询数据
        WorkType workType = workTypeMapper.selectById(id);
        if (workType == null) {
            return CommonResult.failed("未找到ID为" + id + "的工种类型");
        }
        return CommonResult.success(workType);
    }

    /**
     * 新增工种类型
     */
    @Override
    public CommonResult<?> saveType(WorkType workType) {
        // 空值校验
        if (workType == null) {
            return CommonResult.failed("提交的数据不能为空");
        }

        // 名称不能为空
        if (!StringUtils.hasText(workType.getTypeName())) {
            return CommonResult.failed("工种类型名称不能为空");
        }

        // 校验名称唯一性
        LambdaQueryWrapper<WorkType> nameWrapper = new LambdaQueryWrapper<>();
        nameWrapper.eq(WorkType::getTypeName, workType.getTypeName());
        if (workTypeMapper.selectCount(nameWrapper) > 0) {
            return CommonResult.failed("工种类型名称已存在");
        }
        workType.setId(null);
        // 执行新增
        int rows = workTypeMapper.insert(workType);
        return rows > 0 ? CommonResult.success("新增工种类型成功") : CommonResult.failed("新增工种类型失败");
    }

    /**
     * 更新工种类型
     */
    @Override
    public CommonResult<?> updateType(WorkType workType) {
        // 空值校验
        if (workType == null) {
            return CommonResult.failed("提交的数据不能为空");
        }
        // ID不能为空
        if (workType.getId() == null) {
            return CommonResult.failed("ID不能为空");
        }
        // 名称不能为空
        if (!StringUtils.hasText(workType.getTypeName())) {
            return CommonResult.failed("工种类型名称不能为空");
        }

        // 校验数据存在性
        WorkType existing = workTypeMapper.selectById(workType.getId());
        if (existing == null) {
            return CommonResult.failed("未找到ID为" + workType.getId() + "的工种类型");
        }

        // 校验名称唯一性（排除当前ID）
        // 构造查询条件：(typeName相等 或 typeCode相等) 且 id不相等
        LambdaQueryWrapper<WorkType> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper
                // 括号内的或条件：typeName等于目标值 或者 typeCode等于目标值
                .and(wrapper -> wrapper
                        .eq(WorkType::getTypeName, workType.getTypeName())
                        .or()
                        .eq(WorkType::getTypeCode, workType.getTypeCode())
                )
                // 额外添加不等于ID的条件（排除自身记录）
                .ne(WorkType::getId, workType.getId());

        if (workTypeMapper.selectCount(queryWrapper) > 0) {
            return CommonResult.failed("工种类型名称或者工种代码已存在");
        }

        // 执行更新
        int rows = workTypeMapper.updateById(workType);
        return rows > 0 ? CommonResult.success("更新工种类型成功") : CommonResult.failed("更新工种类型失败");
    }

    /**
     * 根据ID删除工种类型
     */
    @Override
    public CommonResult<?> removeById(Long id) {
        // 空值校验
        if (id == null) {
            return CommonResult.failed("ID不能为空");
        }
        // 校验数据存在性
        WorkType existing = workTypeMapper.selectById(id);
        if (existing == null) {
            return CommonResult.failed("未找到ID为" + id + "的工种类型");
        }
        // 执行删除
        int rows = workTypeMapper.deleteById(id);
        return rows > 0 ? CommonResult.success("删除工种类型成功") : CommonResult.failed("删除工种类型失败");
    }

    /**
     * 查询所有工种类型（不分页）
     */
    @Override
    public CommonResult<List<WorkType>> getAll() {
        LambdaQueryWrapper<WorkType> queryWrapper = new LambdaQueryWrapper<>();
        // 按ID升序排序
        queryWrapper.orderByAsc(WorkType::getId);
        // 查询所有数据
        List<WorkType> workTypeList = workTypeMapper.selectList(queryWrapper);
        return CommonResult.success(workTypeList);
    }

    @Override
    public Map<Long, String> IdToNameMap() {
        // 查询所有区域记录（省/市/区）
        List<WorkType> workTypes = workTypeMapper.selectList(null);

        // 处理空列表情况
        if (workTypes == null || workTypes.isEmpty()) {
            return new HashMap<>(0);
        }

        // 转换为ID-名称映射Map
        return workTypes.stream()
                .collect(Collectors.toMap(
                        WorkType::getId,        // 工作类型Id
                        WorkType::getTypeName,  // 值：工作类型名称
                        (existing, replacement) -> existing  // 处理ID重复（保留第一条）
                ));
    }
}